package com.wxq.product.service.impl;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wxq.product.dao.CategoryBrandRelationDao;
import com.wxq.product.entity.CategoryBrandRelationEntity;
import com.wxq.product.dao.BrandDao;
import com.wxq.product.entity.BrandEntity;
import com.wxq.product.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxq.common.utils.PageUtils;
import com.wxq.common.utils.Query;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.eq("band_id", key).or().like("naem", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );


        return new PageUtils(page);
    }

    /**
     * 级联更新品牌
     *
     * @param brand
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateCascade(BrandEntity brand) {
        // 保证数据表冗余字段的数据一致
        // 更新品牌表的数据
        this.updateById(brand);
        if (!StringUtils.isEmpty(brand.getName())) {
            // 同步更新品牌分类关联表中的数据
            CategoryBrandRelationEntity categoryBrandRelationEntity = new
                    CategoryBrandRelationEntity();
            categoryBrandRelationEntity.setBrandId(brand.getBrandId());
            categoryBrandRelationEntity.setBrandName(brand.getName());
            categoryBrandRelationDao.update(categoryBrandRelationEntity,
                    new UpdateWrapper<CategoryBrandRelationEntity>()
                            .eq("brand_id", brand.getBrandId()));
            // TODO 更新其他关联 }
        }

    }

}